package com.black.order.service.impl;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.black.order.feign.ProductFeignClient;
import com.black.order.service.OrderService;
import com.black.order.bean.Order;
import com.black.product.bean.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @Author: Young
 * @CreateTime: 2025-07-29
 * @Description:
 * @Version: 1.0
 */
@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    DiscoveryClient discoveryClient;

    @Autowired
    RestTemplate restTemplate;

    @Autowired
    ProductFeignClient productFeignClient;

    @SentinelResource(value = "createOrder",blockHandler = "createOrderBlockHandler")
    @Override
    public Order createOrder(Long userId, Long productId) {
        //使用feign发起远程调用
        Product product = productFeignClient.getProductById(productId, "Bearer 123456");
//        Product product = getProduct(productId);
        Order order = new Order();
        order.setId(product.getId());
        order.setUserId(userId);
        order.setNickName("zhangsan");
        order.setAddress("合肥");
        order.setProducts(Arrays.asList(product));
        return order;
    }

    private Product getProduct(Long productId) {
        List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
        ServiceInstance instance = instances.get(0);
        String host = "http://" + instance.getHost() + ":" + instance.getPort()+"/product/"+productId;
        Product product = restTemplate.getForObject(host, Product.class);
        return product;
    }

    public Order createOrderBlockHandler(Long userId, Long productId, BlockException blockException) {
        Order order = new Order();
        order.setId(productId);
        order.setUserId(userId);
        order.setNickName("sentinel流控");
        order.setAddress("系统流控");
        return order;
    }


}
